#include "msg.h"

z_log z_log_init(char *p)
{
	z_log tmp;
	if (access(p, W_OK) != 0)
		tmp.f = fopen(p, "w");
	else
		tmp.f = fopen(p, "a");
	return tmp;
}

z_log z_log_init_with_file(FILE *f)
{
	z_log tmp = {f};
	return tmp;
}

int z_log_release(z_log l)
{
	if (l.f != stdout && l.f != stderr)
		fclose(l.f);
	return 0;
}

FILE *z_log_file_get(z_log *l)
{
	return l->f;
}

z_time z_now()
{
	time_t t = time(NULL);
	struct tm *tmp = localtime(&t);
	return (z_time)tmp;
}

char *z_timestr(z_time t)
{
	struct tm *tmp = (struct tm *)t;
	char *buf = (char *)malloc(sizeof(char)*64);
	memset(buf, 0, sizeof(char)*64);
	strftime(buf, sizeof(char)*64, "%D %T", tmp);
	return buf;
}

z_msg z_msg_init(int c, char *m)
{
	z_msg tmp = {
		z_now(),
		c,
		m
	};

	return tmp;
}

int z_msg_release(z_msg m)
{
	return 0;
}

int z_msg_dump(z_log *l, z_msg *m)
{
	fprintf(z_log_file_get(l), "%s %i] %s\n", z_timestr(m->time), m->code, m->msg);
	return 0;
}

int z_msg_eval(z_msg *m)
{
	if (m->code < 0)
		_exit(-m->code);
	return 0;
}

